import { useEffect, useState } from "react";
import Demo7 from "./components/demo7";
import myContext from "./components/demo7/context";

const App = () => {
  const [currentTheme, setCurrentTheme] = useState({
    name: "明亮",
    theme: "light",
  });

  const themeList = [
    {
      name: "明亮",
      theme: "light",
    },
    {
      name: "黑暗",
      theme: "drak",
    },
  ];

  useEffect(() => {
    const media = window.matchMedia("(prefers-color-scheme:dark)");

    if (media.matches) {
      setCurrentTheme(themeList[1]);
      document.documentElement.className = themeList[1].theme;
    } else {
      setCurrentTheme(themeList[0]);
      document.documentElement.className = themeList[0].theme;
    }

    media.addEventListener("change", () => {
      if (media.matches) {
        setCurrentTheme(themeList[1]);
        document.documentElement.className = themeList[1].theme;
      } else {
        setCurrentTheme(themeList[0]);
        document.documentElement.className = themeList[0].theme;
      }
    });
  }, []);

  // 保存鼠标点击位置
  const [clickPosition, setClickPosition] = useState({ clientX: 0, clientY: 0 });

  return (
    <myContext.Provider
      value={{
        currentTheme,
        themeList,
        setCurrentTheme(value, e?: MouseEvent) {
          // 保存鼠标点击位置
          if (e) {
            setClickPosition({ clientX: e.clientX, clientY: e.clientY });
          }

          // 获取到 transition API 实例
          const transition = document.startViewTransition(() => {
            document.documentElement.className = value.theme
          });

          // 在 transition.ready 的 Promise 完成后，执行自定义动画
          transition.ready.then(() => {
            // 由于我们要从鼠标点击的位置开始做动画，所以我们需要先获取到鼠标的位置
            const { clientX, clientY } = e || clickPosition;

            // 计算半径，以鼠标点击的位置为圆心，到四个角的距离中最大的那个作为半径
            const radius = Math.hypot(
              Math.max(clientX, innerWidth - clientX),
              Math.max(clientY, innerHeight - clientY)
            );
            const clipPath = [
              `circle(0% at ${clientX}px ${clientY}px)`,
              `circle(${radius}px at ${clientX}px ${clientY}px)`,
            ];
            const isDark = document.documentElement.classList.contains("dark");
            // 自定义动画
            document.documentElement.animate(
              {
                // 如果要切换到暗色主题，我们在过渡的时候从半径 100% 的圆开始，到 0% 的圆结束
                clipPath: isDark ? clipPath.reverse() : clipPath,
              },
              {
                duration: 500,
                // 如果要切换到暗色主题，我们应该裁剪 view-transition-old(root) 的内容
                pseudoElement: isDark
                  ? "::view-transition-old(root)"
                  : "::view-transition-new(root)",
              }
            );
          });
        },
      }}
    >
      <div>
        <div>
          <div>
            <Demo7></Demo7>
          </div>
        </div>
      </div>
    </myContext.Provider>
  );
};

export default App;
